package com.hospital.data.simulation.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hospital.common.pojo.TUser;
import com.hospital.data.simulation.exception.UserServiceException;
import com.hospital.data.simulation.exception.enums.UserServiceExpCode;
import com.hospital.data.simulation.mapper.TUserMapper;
import com.hospital.data.simulation.service.TUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements TUserService{
    @Autowired
    private TUserMapper tUserMapper;
    @Override
    public Long addUser(TUser user) {
        if(tUserMapper.insert(user) ==0){
            throw new UserServiceException(UserServiceExpCode.ADD_USER_FAILED);
        }
        return user.getId();
    }

    @Override
    public void deleteUser(Long id) {
        if(tUserMapper.deleteById(id) ==0){
            throw new UserServiceException(UserServiceExpCode.DELETE_USER_FAILED);
        }
    }

    @Override
    public void updateUser(TUser user) {
        LambdaUpdateWrapper<TUser> wrapper = new LambdaUpdateWrapper<>();
        constructWrapper(wrapper,user);
        if(tUserMapper.update(wrapper) ==0){
            throw new UserServiceException(UserServiceExpCode.UPDATE_USER_FAILED);
        }
    }
    private void constructWrapper(LambdaUpdateWrapper<TUser> wrapper,TUser user){
        wrapper.eq(TUser::getId,user.getId());
        if(!ObjectUtils.isEmpty(user.getPassword())){
            wrapper.set(TUser::getPassword,user.getPassword());
        }
        if(!ObjectUtils.isEmpty(user.getInfoId())){
            wrapper.set(TUser::getInfoId,user.getInfoId());
        }
        if(!ObjectUtils.isEmpty(user.getSex())){
            wrapper.set(TUser::getSex,user.getSex());
        }
        if(!ObjectUtils.isEmpty(user.getPhone())){
            wrapper.set(TUser::getPhone,user.getPhone());
        }
        if(!ObjectUtils.isEmpty(user.getInit())){
            wrapper.set(TUser::getInit,user.getInit());
        }
        if(!ObjectUtils.isEmpty(user.getName())){
            wrapper.set(TUser::getName,user.getName());
        }
    }
}
